package com.das.mechanic_base.widget;

import android.content.Context;
import android.graphics.Rect;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.res.ResourcesCompat;

import com.das.mechanic_base.R;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.base.X3BaseBottomSheetDialog;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.SoftKeyboardStateHelper;
import com.das.mechanic_base.utils.X3DateUtils;
import com.das.mechanic_base.utils.X3NumberTextWatcher;
import com.das.mechanic_base.utils.X3ScreenUtils;
import com.das.mechanic_base.utils.X3StringUtils;
import com.umeng.analytics.MobclickAgent;
import com.zyyoona7.wheel.WheelView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class X3HomeChangeMileDialog extends X3BaseBottomSheetDialog implements View.OnClickListener, ViewTreeObserver.OnGlobalLayoutListener {

    private WheelView<String> totalWheel;
    private WheelView<String> perWheel;
    private EditText et_total;
    private EditText et_per;
    private TextView tv_unit;
    private TextView tv_notice;
    private ImageView iv_add;
    private ImageView iv_cute;
    private X3MemberButtonView mv_view;

    List<Integer> mList;

    private List<String> perList;

    private long startTime, startPerTime;
    public X3NumberTextWatcher textWatcher, textPerWatcher;
    private InputMethodManager imm;
    private int perMiles;
    private String modelTime;
    private long days;
    private String km;
    private boolean customSet;
    private List<Integer> pList;
    private String permile;
    private float y1;
    private float y2;
    private boolean isTouchFrom;
    private float ytotal1;
    private float ytotal2;
    private View decorView;

    @Override
    protected int getLayoutId() {
        return R.layout.x3_home_change_mile_dialog;
    }

    public X3HomeChangeMileDialog(@NonNull Context context) {
        super(context);
    }

    @Override
    protected boolean getDialogCancel() {
        return false;
    }

    @Override
    protected void initView() {

        totalWheel = getView(R.id.wv_total);
        perWheel = getView(R.id.wv_per);
        et_total = getView(R.id.et_total);
        et_per = getView(R.id.et_per);
        tv_unit = getView(R.id.tv_unit);
        tv_notice = getView(R.id.tv_notice);
        iv_add = getView(R.id.iv_add);
        iv_cute = getView(R.id.iv_cute);
        mv_view = getView(R.id.mv_view);

        iv_add.setOnClickListener(this);
        iv_cute.setOnClickListener(this);
        mv_view.setOnClickListener(this);
        imm = (InputMethodManager) mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
        km = (String) SpHelper.getData(X3Constent.MILEAGEUNIT, "km");
        tv_unit.setText(km);

        decorView = getWindow().getDecorView();
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(this);

        mList = new ArrayList<>();

        for (int i = 0; i < 10; i++) {
            mList.add(i * 100);
        }

        for (int i = 1; i < 100; i++) {
            mList.add(i * 1000);
        }

        for (int i = 10; i <= 100; i++) {
            mList.add(i * 10000);
        }

        initWheel();
        et_total.setVisibility(View.VISIBLE);
        new Handler().postDelayed(() -> {
            et_total.setFocusable(true);
            et_total.setFocusableInTouchMode(true);
            et_total.requestFocus();
            String selectedItemData = (String) totalWheel.getSelectedItemData();
            totalWheel.setVisibility(View.GONE);
            et_total.setText(selectedItemData);
            if (!X3StringUtils.isEmpty(selectedItemData)) {
                et_total.setSelection(selectedItemData.length());
            }
            InputMethodManager inputManager =
                    (InputMethodManager) et_total.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.showSoftInput(et_total, 0);
        }, 800);
    }

    /**
     * 初始化滑动控件
     */
    private void initWheel() {
        totalWheel.setTypeface(ResourcesCompat.getFont(mContext, R.font.din_text_type));
        totalWheel.setSoundEffectResource(R.raw.x3_button_choose);
        totalWheel.setSoundEffect(true);
        totalWheel.setPlayVolume(0.5f);

        perWheel.setTypeface(ResourcesCompat.getFont(mContext, R.font.din_text_type));
        perWheel.setSoundEffectResource(R.raw.x3_button_choose);
        perWheel.setSoundEffect(true);
        perWheel.setPlayVolume(0.5f);

        totalWheel.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    startTime = System.currentTimeMillis();
                    ytotal1 = event.getY();
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    long endTime = System.currentTimeMillis();
                    ytotal2 = event.getY();
                    if (endTime - startTime < 200 && Math.abs(ytotal1 - ytotal2) < 50) {
                        getFocusable(et_total, totalWheel, true);
                    }
                    break;
            }
            return false;
        });

        totalWheel.setOnWheelChangedListener(new WheelView.OnWheelChangedListener() {
            @Override
            public void onWheelScroll(int scrollOffsetY) {

            }

            @Override
            public void onWheelItemChanged(int oldPosition, int newPosition) {

            }

            @Override
            public void onWheelSelected(int position) {
                String selectedItemData = totalWheel.getSelectedItemData().replaceAll(",", "");
                showTotalMiles(selectedItemData);
            }

            @Override
            public void onWheelScrollStateChanged(int state) {

            }
        });

        et_total.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                getFocusable(et_total, totalWheel, false);
            }

            return false;
        });
        perWheel.setOnTouchListener((v, event) -> {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    startPerTime = System.currentTimeMillis();
                    y1 = event.getY();

                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    long endTime = System.currentTimeMillis();
                    y2 = event.getY();
                    if (endTime - startPerTime < 200 && Math.abs(y1 - y2) < 50) {
                        getPerFocusable(et_per, perWheel, true);
                    } else {
                        isTouchFrom = true;
                    }
                    customSet = true;
                    break;
            }
            return false;
        });


        perWheel.setOnWheelChangedListener(new WheelView.OnWheelChangedListener() {
            @Override
            public void onWheelScroll(int scrollOffsetY) {

            }

            @Override
            public void onWheelItemChanged(int oldPosition, int newPosition) {

            }

            @Override
            public void onWheelSelected(int position) {
//                String selectedItemData = perWheel.getSelectedItemData().replaceAll(",","");
//                showPerMile(selectedItemData);

                if (isTouchFrom && !X3StringUtils.isEmpty(modelTime)) {
                    int days = X3DateUtils.getDayTimeAfter(modelTime);
                    int cperMiles = (int) Math.ceil(Double.parseDouble(totalWheel.getSelectedItemData().replace(",", "").replace(".","")) / days);
                    tv_notice.setText(String.format(mContext.getString(R.string.x3_mile_change_notice_per), cperMiles + "" + km));
                }

            }

            @Override
            public void onWheelScrollStateChanged(int state) {

            }
        });

        et_per.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                getPerFocusable(et_per, perWheel, false);
            }
            return false;
        });

        textWatcher = new X3NumberTextWatcher(et_total);
        et_total.addTextChangedListener(textWatcher);
        setListenerFotEditText(et_total);
        textWatcher.setiOnGetNumber(new X3NumberTextWatcher.IOnGetNumber(){

            @Override
            public void iOnGetNumber(String value) {
                value = value.replaceAll(",", "");
                showTotalMiles(value);
            }
        });

        textPerWatcher = new X3NumberTextWatcher(et_per);
        et_per.addTextChangedListener(textPerWatcher);
    }

    private void setListenerFotEditText(View view) {
        SoftKeyboardStateHelper softKeyboardStateHelper = new SoftKeyboardStateHelper(view);
        softKeyboardStateHelper.addSoftKeyboardStateListener(new SoftKeyboardStateHelper.SoftKeyboardStateListener() {
            @Override
            public void onSoftKeyboardOpened(int keyboardHeightInPx) {
                //键盘打开
                System.out.println("键盘打开");
            }

            @Override
            public void onSoftKeyboardClosed() {
                System.out.println("键盘关闭");
                //键盘关闭
                if (et_total.isFocusable()) {
                    getFocusable(et_total, totalWheel, false);
                }
            }
        });
    }

    private void getFocusable(EditText editText, WheelView wheelView, boolean hasFocus) {
        if (hasFocus) {
            String selectedItemData = (String) wheelView.getSelectedItemData();
            wheelView.setVisibility(View.GONE);
            editText.setVisibility(View.VISIBLE);
            editText.setFocusable(true);
            editText.setCursorVisible(true);
            editText.setHint("");
            editText.requestFocus();
            editText.setText(selectedItemData);
            if (!X3StringUtils.isEmpty(selectedItemData)) {
                editText.setSelection(selectedItemData.length());
            }
            imm.showSoftInput(editText, 0);
        } else {
            editText.setVisibility(View.GONE);
            wheelView.setVisibility(View.VISIBLE);
            String value = editText.getText().toString().replaceAll(",", "");
            showTotalMiles(value);
        }
    }

    private void showTotalMiles(String value) {
        value = value.replace(".","");
        if (!X3StringUtils.isEmpty(value)) {
            if (Integer.parseInt(value) > 1000000) {
                value = "1000000";
            }
            addTotalMile(Integer.parseInt(value));

            if (days > 0) {
//                perMiles = (int) (Integer.parseInt(value) / days);
                perMiles = (int) Math.ceil(Double.parseDouble(value) / days);
                if (perMiles > 1000) {
                    perMiles = 1000;
                }

//                addPerMile(perMiles);
                if (!customSet) {
                    addPerMile(perMiles);
                }

            }
        } else {
            perMiles = 0;
            addPerMile(perMiles);
        }
//        if (!StringUtils.isEmpty(modelTime)) {
//            int days = DateUtils.getDayTimeAfter(modelTime);
//            int cperMiles = (int) Math.ceil(Double.parseDouble(totalWheel.getSelectedItemData().replace(",","")) / days);
//            tv_notice.setText(String.format(mContext.getString(R.string.mile_change_notice_per),cperMiles+""+km));
//        }
    }

    private void getPerFocusable(EditText editText, WheelView wheelView, boolean hasFocus) {
        System.out.println("执行了" + hasFocus);
        if (hasFocus) {
            String selectedItemData = (String) wheelView.getSelectedItemData();
            wheelView.setVisibility(View.GONE);
            editText.setVisibility(View.VISIBLE);
            editText.setFocusable(true);
            editText.setCursorVisible(true);
            editText.setHint("");
            editText.requestFocus();
            editText.setText(selectedItemData);
            if (!X3StringUtils.isEmpty(selectedItemData)) {
                editText.setSelection(selectedItemData.length());
            }
            imm.showSoftInput(editText, 0);
        } else {
            editText.setVisibility(View.GONE);
            wheelView.setVisibility(View.VISIBLE);
            String value = editText.getText().toString().replaceAll(",", "");
            showPerMile(value);
        }
    }

    private void showPerMile(String value) {
        if (!X3StringUtils.isEmpty(value)) {
            perMiles = Integer.parseInt(value);
            if (perMiles > 1000) {
                perMiles = 1000;
            }
            System.out.println("集合的初始化");
            addPerMile(perMiles);
        }

//        if (!StringUtils.isEmpty(modelTime)) {
//           int days = DateUtils.getDayTimeAfter(modelTime);
//            int cperMiles = (int) Math.ceil(Double.parseDouble(totalWheel.getSelectedItemData().replace(",","")) / days);
//            tv_notice.setText(String.format(mContext.getString(R.string.mile_change_notice_per),cperMiles+""+km));
//        }


    }

    @Override
    protected void hideKeyboard(IBinder token) {
        super.hideKeyboard(token);

        if (et_total.isFocusable()) {
            getFocusable(et_total, totalWheel, false);
        }
        if (et_per.isFocusable()) {
            getPerFocusable(et_per, perWheel, false);
        }
    }

    /**
     * 传入总里程和出厂时间  是否手动修改日均  日均里程
     *
     * @param totalMile
     * @param modelTime
     */
    public void showTotalAndTime(int totalMile, String modelTime, boolean customSet, String permile) {
        this.modelTime = modelTime;
        this.customSet = customSet;
        this.permile = permile;
        addTotalMile(totalMile);

        if (!X3StringUtils.isEmpty(modelTime)) {
            days = X3DateUtils.getDayTimeAfter(modelTime);
            perMiles = (int) (totalMile / days);
            if (perMiles > 1000) {
                perMiles = 1000;
            }
        } else {
            perMiles = 4;
        }

//        if(customSet){
//            int permiles = (int) Double.parseDouble(permile);
//            addPerMile(permiles);
//        }else {
//            addPerMile(perMiles);
//        }
        if (X3StringUtils.isEmpty(permile)) {
            addPerMile(perMiles);
        } else {
            int perMiles = (int) Double.parseDouble(permile);
            addPerMile(perMiles);
        }

    }


    /**
     * 添加日均里程集合
     *
     * @param perMiles
     */
    private void addPerMile(int perMiles) {
        perList = new ArrayList<>();
        pList = new ArrayList<>();
        if (perMiles < 5) {
            for (int i = 0; i < 11; i++) {
                pList.add(i);
            }
        } else {
            pList.add(perMiles);
            int cuteMile = (int) (perMiles * 0.1);  // 5 -- 9
            if (cuteMile == 0) {
                cuteMile = 1;
            }

            if (perMiles < 1000) {
                for (int i = 0; i < 5; i++) {
                    int afterMile = perMiles + cuteMile * (i + 1);
                    if (afterMile >= 1000) {
                        pList.add(1000);
                        break;
                    } else {
                        pList.add(afterMile);
                    }
                }
            }

            for (int i = 0; i < 5; i++) {
                int afterMile = perMiles - cuteMile * (i + 1);
                pList.add(afterMile);
            }
        }
        Collections.sort(pList);
        Collections.reverse(pList);

        for (int i : pList) {
            perList.add(i + "");
        }
        System.out.println("集合" + perList.toString());
        isTouchFrom = false;
        perWheel.setData(perList);
        perWheel.setSelectedItemPosition(pList.indexOf(perMiles));

    }

    /**
     * 添加总里程到数据列表中
     *
     * @param totalMile
     */
    private void addTotalMile(int totalMile) {
        List<Integer> allMile = mList;
        int index = 0;
        if (!allMile.contains(totalMile)) {
            allMile.add(totalMile);
        }
        Collections.sort(allMile);
        Collections.reverse(allMile);
        index = allMile.indexOf(totalMile);

        List<String> dataList = new ArrayList<>();
        for (Integer mile : allMile) {
            dataList.add(X3StringUtils.num2thousand(mile + ""));
        }

        totalWheel.setData(dataList);
        totalWheel.setSelectedItemPosition(index);
    }
//
//    @Override
//    protected int getDialogHeight() {
//        return (int) (ScreenUtils.getScreenHeight(mContext) * 0.7);
//    }

    @Override
    public void onClick(View v) {


        int id = v.getId();
        if (id == R.id.iv_cute) {
            int size = perList.size();
            int selectedItemPosition = perWheel.getSelectedItemPosition();
            if ((selectedItemPosition - 1) >= size) {
                return;
            }
            perWheel.setSelectedItemPosition(selectedItemPosition + 1);
            customSet = true;
            if (!X3StringUtils.isEmpty(modelTime)) {
                int days = X3DateUtils.getDayTimeAfter(modelTime);
                int cperMiles = (int) Math.ceil(Double.parseDouble(totalWheel.getSelectedItemData().replace(",", "").replace(".", "")) / days);
                tv_notice.setText(String.format(mContext.getString(R.string.x3_mile_change_notice_per), cperMiles + "" + km));
            }
        } else if (id == R.id.iv_add) {
            int selectedItemPositionadd = perWheel.getSelectedItemPosition();
            if ((selectedItemPositionadd - 1) < 0) {
                return;
            }
            perWheel.setSelectedItemPosition(selectedItemPositionadd - 1);
            customSet = true;
            if (!X3StringUtils.isEmpty(modelTime)) {
                int days = X3DateUtils.getDayTimeAfter(modelTime);
                int cperMiles = (int) Math.ceil(Double.parseDouble(totalWheel.getSelectedItemData().replace(",", "").replace(".", "")) / days);
                tv_notice.setText(String.format(mContext.getString(R.string.x3_mile_change_notice_per), cperMiles + "" + km));
            }
        } else if (id == R.id.mv_view) {
            if (ionClickChangeMile != null) {
                ionClickChangeMile.onSaveChangeMiles(totalWheel.getSelectedItemData().replace(",", "").replace(".", ""), perWheel.getSelectedItemData(), customSet);
            }
            dismiss();
        }
    }

    private final Rect r =new Rect();

    private int oldDiff = 0;

    @Override
    public void onGlobalLayout() {
        decorView.getWindowVisibleDisplayFrame(r);
        int diff = decorView.getRootView().getHeight() -r.height();
        //键盘是否弹出
        boolean isOpen = (diff > X3ScreenUtils.dipToPx(100,mContext));
        RelativeLayout.LayoutParams viewLayout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,X3ScreenUtils.dipToPx(44,mContext));
        if(diff != oldDiff){
            Log.d("SSSS", "键盘是否弹起: "+isOpen + "::" + diff + "::" + X3ScreenUtils.dipToPx(100,mContext));
            oldDiff = diff;
            viewLayout.leftMargin = X3ScreenUtils.dipToPx(20,mContext);
            viewLayout.rightMargin = X3ScreenUtils.dipToPx(20,mContext);
            if (isOpen) {
                viewLayout.addRule(RelativeLayout.BELOW,R.id.rl_per);
                viewLayout.topMargin = X3ScreenUtils.dipToPx(20,mContext);
            }else {
                viewLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
            }
            mv_view.setLayoutParams(viewLayout);
        }
    }


    public interface IonClickChangeMile {
        void onSaveChangeMiles(String selectedTotalItemData, String selectedPerItemData, boolean onSaveChangeMiles);
    }

    IonClickChangeMile ionClickChangeMile;

    public void setOnSaveChangeMiles(IonClickChangeMile ionClickChangeMile) {
        this.ionClickChangeMile = ionClickChangeMile;
    }
    @Override
    protected void onStart() {
        super.onStart();
        MobclickAgent.onPageStart("车辆总里程弹窗");
    }

    @Override
    protected void onStop() {
        super.onStop();
        MobclickAgent.onPageEnd("车辆总里程弹窗");
    }
}
